<template>
	<div class="pie-wrap">
		<show-view-path :parent-views="mapParentViews" :screenConfig="screenConfig" :chartConfig="chartConfig" @selectView="selectView"></show-view-path>
		<div style="flex: 1" :ref="config.key"></div>
	</div>
</template>

<script>
import ChartPublic from "@/views/modules/preview/components/char-component/chart-public.js";
import * as echarts from 'echarts';

export default {
	name: "MapComponent",
	mixins:[ChartPublic],
	data() {
		return {
			chartType:"map",
			mapParentViews:[],
            mapTypeDown:'',
		}
	},
	methods: {
		// 路由懒加载
        loadMapView(map)  {
            var path = import.meta.env.JPAAS_MAP_CONTEXT;
            var promise = new Promise(function(resolve){
                let url=`${path}/province/${map}.json`;
                fetch(url).then(response => {
                    resolve(response.json());
                })
            })
            return promise;
        },
		async setOption() {
            let mapType = "china";
            if (this.config.styles.mapType == "province" || this.config.styles.mapType == "custom") {
                mapType = this.config.styles.province;
            } else if (this.drillDownValue) {
                let obj = this.mapTypes.find(item => item.label == this.drillDownValue);
                mapType = obj.value;
            }else if(this.mapTypeDown){
                let obj = this.mapTypes.find(item => item.label == this.mapTypeDown);
                mapType = obj.value;
            }
            let json = await this.loadMapView(mapType);
            echarts.registerMap(mapType, json);
            let data = this.getMapData();
            let tooltip = {
                show: this.config.styles ? this.config.styles.tooltipShow : false,
                trigger: 'item',
                borderColor: this.config.styles.tooltipConfig.borderColor,
                backgroundColor: this.config.styles.tooltipConfig.raBgColor,
                borderWidth: this.config.styles.tooltipConfig.borderWidth,
                textStyle: {
                    fontSize: this.config.styles.tooltipConfig.fontSize,
                    color: this.config.styles.tooltipConfig.fontColor,
                    fontWeight: this.config.styles.tooltipConfig.fontStyle
                },
                formatter: function (params) {
                    let res = params.name + '<br/>';
                    for (let i = 0; i < data.length; i++) {
                        if (data[i].name == params.name) {
                            let values = data[i].values || [];
                            for (let j = 0; j < values.length; j++) {
                                res += values[j].name + ' : ' + values[j].value + '</br>';
                            }
                        }
                    }
                    return res;
                }
            };
            let styles = this.config.styles;
            let series = {
                name: this.config.title,
                type: 'map',
                mapType: mapType, // 自定义扩展图表类型
                roam: false, //是否开启平游或缩放
                zoom: 1.2,
                itemStyle: {
                    areaColor: styles.areaConfig.areaColor,
                    borderType: styles.areaConfig.borderType,
                    borderSize: styles.areaConfig.borderSize,
                    borderWidth: styles.areaConfig.borderWidth || 1,
                    borderColor: styles.areaConfig.borderColor
                },
                emphasis: {
                    disabled: !styles.areaConfig.focus,
                    itemStyle: {
                        areaColor: styles.areaConfig.focusColor,
                    },
                    label: {
                        color: styles.areaConfig.fontColor
                    }
                },
                select: {
                    disabled: !styles.areaConfig.focus,
                    itemStyle: {
                        areaColor: styles.areaConfig.focusColor,
                    },
                    label: {
                        color: styles.areaConfig.fontColor
                    }
                },
                data: data
            };
            //标签
            if (styles.showLabel) {
                series.label = {
                    show: styles.showLabel,
                    fontSize: styles.labelConfig.fontSize,
                    color: styles.labelConfig.fontColor,
                }
            }
            let geo = null;
            //阴影
            if (styles.showShadow) {
                geo = {
                    type: 'map',
                    roam: false,
                    map: mapType,
                    zoom: 1.2,
                    itemStyle: {
                        normal: {
                            shadowColor: styles.shadowConfig.shadowColor,
                            shadowOffsetX: styles.shadowConfig.shadowOffsetX,
                            shadowOffsetY: styles.shadowConfig.shadowOffsetY
                        },
                    },
                }
            }
            this.mapTypeDown = "";
            this.option = {
                tooltip: tooltip,
                visualMap: this.getVisualMap(),
                geo: geo,
                series: series
            }
        },
		getMapData(){
			/**
			 *  {
                name: '广东省',
                itemStyle: {
                    normal: {
                        areaColor: '#FBE0EC'
                    }
                },
                values:[
                    {"name": "广州市", "value": 200},
                    {"name": "深圳市", "value": 500},
                    {"name": "东莞市", "value": 100}
                ]
            }
			 */
			let data=[];
			//静态数据模式
			if(this.config.dataSources.source=="static") {
				if (this.config.dataSources.staticData) {
					//静态数据
					let staticData = JSON.parse(this.config.dataSources.staticData);
					let newData=[];
					for (let i = 0; i < staticData.length; i++) {
						let obj={
							name:staticData[i].name,
							values:staticData[i].values,
							itemStyle:{
								normal: {
									areaColor: staticData[i].areaColor
								}
							}
						}
						newData.push(obj);
					}
					data=newData;
				}
			}else {
				if(!this.config.dataSources.dimensions || this.config.dataSources.dimensions.length==0){
					return data;
				}
				for (let i = 0; i < this.data.length; i++) {
					let obj={};
					//地址字段
					let dimension=this.config.dataSources.dimensions[0];
					let fieldName=dimension.tableName?dimension.tableName+'_'+dimension.fieldName:dimension.fieldName
					let dimensionVal= this.data[i][fieldName];
					//配置了字段渲染
					if(dimensionVal && typeof(dimensionVal) !="string"){
						obj.name=dimensionVal.newValue;
						dimensionVal=dimensionVal.oldValue;
					}else {
						obj.name=dimensionVal;
					}
					let values=[];
					//获取度量
					for (let j = 0; j < this.config.dataSources.measures.length; j++) {
						let measure=this.config.dataSources.measures[j];
						let fieldName=measure.tableName?measure.tableName+'_'+measure.fieldName:measure.fieldName;
						let measureVal= this.data[i][fieldName];
						values.push({
							name:measure.fieldLabel,
							value:measureVal
						});
					}
					obj.values=values;
					if(values.length>0){
						obj.value=values[0].value
					}else {
						obj.value=0
					}
					data.push(obj);
				}
			}
			return data;
		},
		/**
		 * 根据值获取颜色
		 * @param value
		 * @param colors
		 */
		getColor(value,colors){
			let color="";
			if((!value && value!=0) || !colors){
				return color;
			}
			for (let i = 0; i < colors.length; i++) {
				switch(colors[i].express_value){
					case 'eq':
						if(value==colors[i].express_name){
							color=colors[i].color;
						}
						break;
					case 'lt':
						if(value<colors[i].express_name){
							color=colors[i].color;
						}
						break;
					case 'le':
						if(value<=colors[i].express_name){
							color=colors[i].color;
						}
						break;
					case 'gt':
						if(value>colors[i].express_name){
							color=colors[i].color;
						}
						break;
					case 'ge':
						if(value>=colors[i].express_name){
							color=colors[i].color;
						}
						break;
					case 'in':
						if(colors[i].express_name<=value && value<=colors[i].express_name2){
							color=colors[i].color;
						}
						break;
				}
				//有颜色后结束循环
				if(color){
					break;
				}
			}
			return color;
		},
		getVisualMap(){
			let visualMap=this.config.styles.visualMap;
			let visualMapConf={
				show:this.config.styles.showVisual,
				type:visualMap.type || 'continuous',
				left: visualMap.position || 'right',
				min: visualMap.min || 0,
				max: visualMap.max || 5000,
				text: [visualMap.maxText, visualMap.minText],// 文本，默认为数值文本
				calculable: visualMap.calculable,
				textStyle: {
					color: visualMap.textColor,
					fontSize:visualMap.fontSize
				}
			}
			//连续型
			if(visualMap.type=='continuous'){
				visualMapConf["inRange"]={
					color:visualMap.colors
				}
			}else {
				for (let i = 0; i < visualMap.colors.length; i++) {
					if(!visualMap.colors[i].label){
						delete visualMap.colors[i].label;
					}
				}
				visualMapConf= {
					show: this.config.styles.showVisual,
					type: visualMap.type || 'continuous',
					left: visualMap.position || 'right',
					pieces: visualMap.colors,
					textStyle: {
						color: visualMap.textColor,
						fontSize: visualMap.fontSize
					}
				}
			}
			return visualMapConf;
		},
		setParentViews(parentViews){
			let self=this;
			setTimeout(function () {
                self.mapParentViews=parentViews;
			},1000)
		}
	},
	watch: {}
}
</script>

<style scoped>
.pie-wrap {
	width: 100%;
	display: flex;
	height: 100%;
	flex-direction: column;
}
</style>
